package factory.one.controller;

import com.alibaba.fastjson2.JSON;
import factory.one.entity.*;
import factory.one.pojo.common.Page;
import factory.one.pojo.common.SqlCondition;
import factory.one.service.*;
import factory.one.utils.StageUtil;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.sql.Types;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author sk.z
 * 2023/8/22
 * 货运
 **/
//@Controller
//@RequestMapping("/send")
@Deprecated
public class SendController {

    private final OrderService orderService;
    private final BatchService batchService;
    private final SendService sendService;
    private final ProductService productService;
    private final CustomService customService;
    private final CountService countService;

    public SendController(OrderService orderService,
                          BatchService batchService,
                          SendService sendService,
                          ProductService productService,
                          CustomService customService,
                          CountService countService) {
        this.orderService = orderService;
        this.batchService = batchService;
        this.productService = productService;
        this.sendService = sendService;
        this.customService = customService;
        this.countService = countService;
    }

    @GetMapping("/list.html")
    public String listHtml(@RequestParam(defaultValue = "1") Integer page,
                           @RequestParam(defaultValue = "10") Integer size,
                           Model model) {
        SqlCondition condition = new SqlCondition("is_confirm = ?", true, Types.BOOLEAN); //已上产线
        List<Order> list = orderService.listByCondition(page, size, Collections.singletonList(condition));
        Integer count = orderService.countByCondition(Collections.singletonList(condition));
        trans(list);
        model.addAttribute("page", new Page<>(list, count, page, size));
        return "send/list";
    }

    @GetMapping("/detail.html")
    public String detailHtml(@RequestParam Long orderId, Model model) {
        Order order = orderService.getById(orderId);
        model.addAttribute("order", order);

        List<Batch> batchList = batchService.list(orderId);
        transBatch(batchList);
        model.addAttribute("batchList", batchList);
        Map<Long, String> batchProductNameMap = batchList.stream().collect(Collectors.toMap(Batch::getId, Batch::getProductName, (k1, k2) -> k1));

        List<Send> sendList = sendService.listByOrder(orderId);
        Map<Integer, List<Send>> sendMap = new HashMap<>();
        for (Send send : sendList) {
            send.setProductName(batchProductNameMap.get(send.getBatchId()));
            if (!sendMap.containsKey(send.getSequence())) {
                sendMap.put(send.getSequence(), new ArrayList<>());
            }
            sendMap.get(send.getSequence()).add(send);
        }
        model.addAttribute("sendMap", sendMap);

        return "send/detail";
    }

    @GetMapping("/send.html")
    public String sendHtml(@RequestParam Long orderId, Model model) {
        List<Batch> batchList = batchService.list(orderId);
        transBatch(batchList);
        model.addAttribute("order", orderService.getById(orderId));
        model.addAttribute("batchList", batchList);
        return "send/send";
    }

    @ResponseBody
    @PostMapping("/send")
    public synchronized String send(@RequestParam Long orderId, @RequestParam String batchJson) {
        String userName = SecurityContextHolder.getContext().getAuthentication().getName();
        Integer nextSequence = sendService.getNextSequence(orderId);
        Date now = new Date();
        if (StringUtils.hasText(batchJson)) {
            List<Send> sendList = JSON.parseArray(batchJson, Send.class);
            sendList.forEach(e -> {
                e.setOrderId(orderId);
                e.setSequence(nextSequence);
                e.setCreateTime(now);
                e.setCreateUser(userName);
                if (e.getNumber() != null && e.getNumber() > 0) {
                    sendService.add(e);
                }
            });
        }
        countService.submit(orderId);
        return "true";
    }

    private void trans(List<Order> list) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        for (Order order : list) {
            Custom custom = customService.getById(order.getCustomId());
            order.setCustomName(custom.getName());
//            StageUtil.build(order);
        }
    }

    private void transBatch(List<Batch> list) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        for (Batch batch : list) {
            Product product = productService.getById(batch.getProductId());
            batch.setProductName(product.getName());
            batch.setAmount(batch.getSendNum() * batch.getPrice());
            batch.setProduceGap(Math.max(0, batch.getOrderNum() - batch.getProduceNum()));
            batch.setSendGap(Math.max(0, batch.getOrderNum() - batch.getSendNum()));
        }
    }

}
